<template>
  <div id="chart" style="position: relative; width: 910px; height: 910px;">
    <div align="center" ref="chartRef" style="position: absolute;width: 910px; height: 910px;top: 50px"></div>
    <div class="legend-container" style="position: absolute; right: -25px; top: 5%; transform: translateY(-50%);height: 100px;display: inline-flex;flex-direction: row;flex-wrap: wrap;justify-content: space-between">
      <div v-for="(color, tissue) in colorPalette" style="padding: 0 10px;" :key="tissue" class="legend-item">
        <svg width="20" height="14">
          <rect width="20" height="14" :fill="color" />
        </svg>
        <span>{{ tissue }}</span>
      </div>
    </div>
  </div>

</template>

<script setup name="Analysis">
  import {reactive} from "@vue/runtime-core";
  import {onMounted, ref} from "vue";
  import data from "@/assets/home/Sample.json"
  import * as echarts from 'echarts';

  const chartRef = ref();
  const chartInstance = ref();

  // 按 Tissue 分类并统计 Sample_type 的个数
  const tissueSampleTypeCounts = data.reduce((acc, item) => {
    if (!acc[item.Tissue]) {
      acc[item.Tissue] = {};
    }
    acc[item.Tissue][item.Sample_type] = (acc[item.Tissue][item.Sample_type] || 0) + 1;
    return acc;
  }, {});

  const tissueSampleTypes = Object.keys(tissueSampleTypeCounts).map(tissue => {
    return Object.keys(tissueSampleTypeCounts[tissue]).map(sampleType => {
      // 找到与当前 sampleType 对应的 Geo_accession
      const geoAccession = data.find(item =>
          item.Sample_type === sampleType && item.Tissue === tissue
      ).Geo_accession;
      const healthStatus = data.find(item =>
          item.Sample_type === sampleType && item.Tissue === tissue
      ).Health_status;
      return {
        value: tissueSampleTypeCounts[tissue][sampleType],
        name: sampleType,
        tissue: tissue,
        healthStatus: healthStatus,
        Geo_accession: geoAccession // 添加 Geo_accession 字段
      };
    });
  }).flat();

  // 提取所有不同的 tissue 类型
  const tissues = Object.keys(tissueSampleTypeCounts);

  let colorPalette = {
    "Plasma": "rgb(58, 228, 238)",
    "Blood": "rgb(173, 41, 236)",
    "Liver": "rgb(208, 116, 90)",
    "Bladder": "rgb(96, 156, 210)",
    "Intestine": "rgb(190, 22, 50)",
    "Ovary": "rgb(247, 5, 5)",
    "Breast": "rgb(87, 151, 18)",
    "Thyroid Gland": "rgb(136, 144, 7)",
    "Brain": "rgb(166, 209, 111)",
    "Bone Marrow": "rgb(163, 182, 207)",
    "Prostate": "rgb(0, 8, 173)",
    "Skin": "rgb(195, 221, 211)",
    "Cervix": "rgb(238, 235, 133)",
    "Peritoneum": "rgb(129, 179, 255)",
    "Kidney": "rgb(67, 172, 17)",
    "Nipple  Aspirate Fluid": "rgb(60, 77, 158)",
    "Lung": "rgb(154, 34, 145)",
    "Pancreas": "rgb(119, 1, 187)",
    "Gastric": "rgb(205, 3, 129)",
    "Cartilage": "rgb(39, 70, 249)",
    "Retina": "rgb(246, 118, 73)",
    "Xenograft Cells Of Acute Lymphoblastic Leukemia": "rgb(161, 224, 150)",
    "Breast  Cancer Pdx Model": "rgb(6, 248, 12)",
    "Oral  ": "rgb(48, 96, 235)",
    "Esophagus": "rgb(99, 180, 231)",
    "Retinal Organoids": "rgb(114, 153, 65)",
    "Pdx Model Colorectal Cancer ": "rgb(195, 128, 245)",
    "Pdx Of Prostate Cancer": "rgb(4, 227, 200)",
    "Nasopharynx": "rgb(186, 112, 185)",
    "Lymph  Node": "rgb(30, 18, 40)"
  };
  const randomIntFromInterval = (min, max) => {
    return Math.floor(Math.random() * (max - min + 1) + min);
  };
  // // 将对象转换为数组，然后按字段名排序
  const sortedColorPaletteArray = Object.entries(colorPalette).sort(([key1], [key2]) => {
    if (key1 < key2) return -1;
    if (key1 > key2) return 1;
    return 0;
  });

  // 将排序后的数组转换回对象
  colorPalette = Object.fromEntries(sortedColorPaletteArray);
  // tissues.forEach(tissue => {
  //   // 随机生成 RGB 值，确保颜色之间有差异
  //   let r = randomIntFromInterval(0, 255); // 红色分量
  //   let g = randomIntFromInterval(0, 255); // 绿色分量
  //   let b = randomIntFromInterval(0, 255); // 蓝色分量
  //
  //   // 确保至少有一个颜色分量与其他颜色有明显差异
  //   while (Math.abs(r - 128) < 30 && Math.abs(g - 128) < 30 && Math.abs(b - 128) < 30) {
  //     r = randomIntFromInterval(0, 255);
  //     g = randomIntFromInterval(0, 255);
  //     b = randomIntFromInterval(0, 255);
  //   }
  //
  //   colorPalette[tissue] = `rgb(${r}, ${g}, ${b})`; // 分配 RGB 颜色
  // });

  // 计算原始数据的最大值和最小值
  const maxOriginal = Math.max(...tissueSampleTypes.map(item => item.value));
  const minOriginal = Math.min(...tissueSampleTypes.map(item => item.value));

  // 定义映射函数
  function mapData(value) {
    // 将原始数据映射到1到10之间
    return 1 + (value - minOriginal) * (10 - 1) / (maxOriginal - minOriginal);
  }

const color = []
  onMounted(()=>{
    console.log(colorPalette)
    console.log(tissueSampleTypes);
    chartInstance.value = echarts.init(chartRef.value);
    const option = {
      backgroundColor: 'white',
      title: {
        // text: 'HSM peak enrichment within tissue DNase-I hypersensitivity sites'
      },
      tooltip: {
        trigger: 'item',
        formatter: function (params) {
          // 注意：这里需要确保 data 数组中每个对象都有对应的字段
          const item = tissueSampleTypes.find(d => d.Geo_accession === params.data.Geo_accession);
          return `
        Number: ${item.value}<br/>
        Sample Type: ${item.name}<br/>
        Tissue: ${item.tissue}<br/>
        Health Status: ${item.healthStatus}
      `;
        }
      },
      // grid: {
      //   left: '5%',
      //   // right: '5%',
      //   bottom: '3px',
      //   containLabel: true
      // },
      // visualMap: {
      //   show: true,
      //   type: 'piecewise',
      //   pieces: tissues.map(tissue => ({
      //     label: tissue,
      //     value: tissue,
      //     color: colorPalette[tissue]
      //   })),
      //   orient: 'vertical',
      //   left: 'left',
      //   top: '0',
      //   text: ['', ''],
      //   calculable: true,
      //   inRange: {} // 设置 inRange 为空对象，这样 visualMap 不会影响图表的展示
      // },
      polar: {
        // 极坐标系的半径和中心位置
        radius: '80%',
        center: ['50%', '50%']
      },
      angleAxis: {
        type: 'category',
        roate: 90,
        data: tissueSampleTypes.sort((a, b) => a.tissue.localeCompare(b.tissue)).map(item => item.name),
        startAngle: 90, // 设置起始角度为-90度，使得极坐标系垂直展示
        boundaryGap: false, // 可以设置为false以让极坐标系无缝连接
        splitLine: {        // 分割线
          show: true,
          lineStyle: {
            color: 'gray',
            type: 'solid'
          }
        },
        axisTick: {
          show: false //是否显示坐标轴刻度。
        },
        axisLine: {         // 坐标轴线
          show: false,
          lineStyle: {
            color: 'gray',
            type: 'solid'
          }
        },
        axisLabel: {
          show:true,
          rotate: 270,
          margin: 15,  // 增加边距
          interval:0, // 显示全部刻度
          color: 'gray',
          fontSize: 10,  // 调整字体大小
          width: 50,
          overflow: 'truncate',
        },
      },
      radiusAxis: {
        //Math.max(...tissueSampleTypes.map(item => item.value))+0.5
        max: 1 +0.1,
        // min:1,
        // max:Math.max(...tissueSampleTypes.map(item => item.value))+0.5,
        axisLine: {         // 坐标轴线
          show: false
        },
        axisTick: {
          show: false //是否显示坐标轴刻度。
        },
        splitLine: {        // 分割线
          show: false
        },
        axisLabel: {
          show:false,
          rotate: 90, // 设置刻度标签垂直展示,没用???
          margin: 15,
          color: 'gray  '
        }
      },
      series: [
        {
          type: 'bar',
          data: tissueSampleTypes.map(item => ({
            // mapData(item.value) 将数据映射到1到10
            value:mapData(item.value),
            name: item.name,
            tissue:item.tissue,
            Geo_accession:item.Geo_accession,
          })),
          coordinateSystem: 'polar',
          name: 'Sample Count',
          label: {
            show: false,
            position: 'middle',
            formatter: '{b}'
          },
          itemStyle: {
            color: function(params) {
              // 根据 tissue 类型返回对应的颜色
              // console.log(params.data.tissue,+":"+colorPalette[params.data.tissue])
              return colorPalette[params.data.tissue];
            }
          }
        }
      ],
      animation: true
    };
    chartInstance.value.setOption(option);
  });


</script>

<style scoped>
.legend-container {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.legend-item {
  display: flex;
  align-items: center;
  margin-bottom: 1px;
}

.legend-item svg {
  margin-right: 10px;
}

.legend-item span {
  font-size: 14px;
  color: #333;
}
</style>
